import {Image, RichText, ScrollView, Text, View} from "@tarojs/components";
import {ActionSheet, Cell, Empty, GridItem, Icon, Swiper, SwiperItem} from "@antmjs/vantui";

import Utils from "@/utils/common";
import RouthPath from "@/common/RouthPath";
import BottomButton from "@/components/bottom_button";
import React, {useCallback, useEffect, useRef, useState} from "react";
import {MachineModel, MachineProjectParams} from "@/common/apis/model";
import AssetImage from "@/common/AssetImage";
import ShowUtils from "@/utils/show_utils";
import {machineListApi} from "@/common/apis/home_datasource";

import LogUtils from "@/utils/log";
import {useShareAppMessage, useShareTimeline} from "@tarojs/taro";
import JsonUtils from "@/utils/json_utils";
import Local_utils from "@/utils/local_utils";
import KefuDialog from "@/components/kefu_dialog";


definePageConfig({
  navigationBarTitleText: '检测项目详情'
})
export default function ProjectDetail() {
  const machineProjectParams = useRef<MachineProjectParams>()
  useShareAppMessage((res) => {
    return {
      title: machineProjectParams.current?.projectId.name, // 分享卡片的title
      path: Utils.getUrlWithObject(RouthPath.projectDetail, {
        machineId: machineProjectParams.current?.machineId,
        projectId: machineProjectParams.current?.projectId
      }), // 分享卡片的小程序路径
      imageUrl: ''
    };
  })
  useShareTimeline(() => {
    // 确保数据已加载
    if (!machineProjectParams.current || !machineProjectParams.current?.projectId) {
      return {
        title: '检测项目详情',
        // query: 'source=timeline_default', // 或者一个空对象，或者不设置query
      };
    }
    const paramsForTimeline: Partial<MachineProjectParams> = {}; // Partial 允许部分属性
    if (machineProjectParams.current?.machineId) {
      paramsForTimeline.machineId = machineProjectParams.current?.machineId; // 传递整个 machineId 对象
    }
    if (machineProjectParams.current?.projectId) {
      paramsForTimeline.projectId = machineProjectParams.current?.projectId; // 传递整个 projectId 对象
    }
    const timelineDataString = JsonUtils.stringify(paramsForTimeline);
    const encodedTimelineData = encodeURIComponent(timelineDataString);
    return {
      title: machineProjectParams.current?.projectId.name,
      query: `data=${encodedTimelineData}`, // <--- 关键修改
      imageUrl: machineProjectParams.current?.projectId.image,
    };
  })

  const machineList = useRef<MachineModel[]>([])
  const [, setRefresh] = useState({})

  const getMachineList = useCallback((id) => {
    machineListApi(id).then((res) => {
      if (res) {
        machineList.current = res;
      }
    })
  }, []);
  const [showMachine, setShowMachine] = useState(false)
  useEffect(() => {
    const params = Utils.getParamsByRouter(Utils.getI())
    if (params && params.data) {
      machineProjectParams.current = Utils.getObjectWithUrl<MachineProjectParams>(params.data)
      setRefresh({})
      if (!(machineProjectParams.current?.machineId)) {
        getMachineList(machineProjectParams.current?.projectId.id)
      }
    }
  }, [getMachineList]);

  const handleMachineSelect = (e) => {
    if (machineProjectParams.current?.projectId) {
      machineProjectParams.current!.projectId.price = e.detail.price
      machineProjectParams.current!.projectId.note = e.detail.note
    }
    //设置了机器
    machineProjectParams.current = {
      projectId: machineProjectParams.current!.projectId,
      machineId: e.detail,
    }
    setShowMachine(false)
    LogUtils.info(machineProjectParams.current)
    Utils.redirectTo({
      url: Utils.getUrlWithObject(RouthPath.projectBook, machineProjectParams.current)
    })
  }


  const getImages = useCallback(() => {
    const p = machineProjectParams.current?.projectId
    let images: string[] = [p!.image];
    if (p?.imageList&&p.imageList.length>0) {
      images = images.concat(p.imageList)
    }else{
      //如果一张图片就在此添加一张
      images.push(p!.image)
      images.push(p!.image)
    }
    return images
  }, []);

  const clickBottomButton = useCallback(() => {
    //判断是否登录
    if (!Local_utils.isLogin()) {
      Utils.navigateTo({
        url: RouthPath.login
      })
      return;
    }
    if (!Local_utils.getMobile()) {
      Utils.modal("完善用户信息", "请完善用户信息后再使用该功能", true, (ok) => {
        if (ok) {
          Utils.navigateTo({
            url: RouthPath.editProfilePage,
          })
        }
      })
      return;
    }
    if (Local_utils.isVIdCard()) {
      if (machineProjectParams.current?.machineId) {
        Utils.redirectTo({
          url: Utils.getUrlWithObject(RouthPath.projectBook, machineProjectParams.current)
        })
      } else {
        setShowMachine(true)
      }
    } else {
      Utils.modal('实名认证', "请先进行实名认证,才能预约", true, (ok) => {
        if (ok) {
          Utils.navigateTo({
            url: RouthPath.realInfoVerify
          })
        }
      })
    }
  }, []);
  const SwiperHeight = "300px"
  const renderContent = useCallback(() => {
    if (machineProjectParams.current && machineProjectParams.current?.projectId) {
      const p = machineProjectParams.current?.projectId
      return (
        p ? <View style={{display: 'flex', flexDirection: 'column'}}>
          <View style={{flex: '1', height: SwiperHeight}}>
            {
              Utils.isEmpty(getImages()) ? null : <Swiper
                height={SwiperHeight}
                width='100%'
                paginationColor='#426543'
                autoPlay='3000'
                initPage={0}
                paginationVisible
              >
                {
                  getImages()?.map((item,index) => (
                    <SwiperItem key={`${item}${index}`}>
                      <Image src={ShowUtils.getImageUrl(item)} radius={15} fit='cover' style={{width: '100%', height: SwiperHeight}} />
                    </SwiperItem>
                  ))
                }
              </Swiper>
            }
          </View>
          <Cell renderTitle={<View
            style={{display: 'flex', flexDirection: 'row', justifyContent: 'space-between'}}
          ><Text
            style={{
              fontSize: '20px',
              fontWeight: 'bold',
              color: 'black'
            }}
          >{p.name}</Text><Text
            style={{
              fontSize: '16px',
              fontWeight: 'bold',
              color: 'red'
            }}
          >{p.price ? ShowUtils.getDefaultPrice(p.price) : ''}</Text></View>}
                label={ShowUtils.getShowNote(p.note)}
          />
          <RichText style={{margin: '10px 0px', backgroundColor: AssetImage.bg, padding: '10px'}}
                    nodes={p.content}
          />
        </View> : <Empty description='暂无数据'/>
      )
    } else {
      return null
    }
  }, []);

  const kefuDialogRef = useRef(null);
  const openDialog = () => {
    // 通过 ref 调用子组件的 setShow 方法
    if (kefuDialogRef.current) {
      kefuDialogRef.current.setShow(true);
    }
  };
  return (
    <View style={{height: '100vh', boxSizing: 'border-box', display: 'flex', flexDirection: 'column'}}>
      <View style={{flex: 1, boxSizing: 'border-box', padding: '0px 10px', position: 'relative', overflow: 'hidden'}}>
        <ScrollView scrollY style={{boxSizing: 'border-box', height: '100%'}}>
          {
            renderContent()
          }
        </ScrollView>
      </View>
      <View style={{display: 'flex', flexDirection: 'row', justifyContent: 'space-between'}}>
        <View
          style={{
            display: 'flex',
            flexDirection: 'column',  // 图标文字纵向排列
            alignItems: 'center',     // 水平居中对齐
            justifyContent: 'center', // 垂直居中对齐
            width: '60px'             // 固定宽度确保布局一致
          }}
          onClick={() => {
            openDialog()
          }}
        >
          <Icon
            name="service"
            size='24px'
            style={{marginBottom: '5px'}}
          />
          <Text style={{fontSize: '12px'}}>客服</Text>
        </View>

        <BottomButton
          margin='15px'
          submitText='立即预约' onSubmit={() => {
          clickBottomButton()
        }}
        ></BottomButton>
      </View>
      <ActionSheet
        show={showMachine}
        actions={machineList.current}
        onClose={() => setShowMachine(false)}
        onSelect={(e) => handleMachineSelect(e)}
      />
      <KefuDialog ref={kefuDialogRef}/>
    </View>
  )
}


